# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from models.enhancedModel import EnhancedModel

import models.city as cm
import views.City as cv
import models.user as um
import decorator as dc
import helpers.maps as maps

class CityContr( webapp.RequestHandler ): # debug
    
    @dc.decorate
    def get(self, action, *params, **kwds):
        
        showArchival = self.request.get( 'archival' ) == 'True'

        permissionName = {"show1" : "ctShow",
                       "showAll" : "ctShow",
                       "edit" : "ctEdit",
                       "delete" : "ctDelete",
                       "new": "ctNew"
                       }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write('<font color=\"red\"><b>You have no rights to do this action.</b></font>')
          return

        if action == 'show1': # show1/id/number # DONE
            query = cm.CityModel.all()
            query.filter( 'ident =', int( params[0] ) )
            query.filter( 'archival =', False )
            if query.count():
                self.response.out.write( cv.show1( um.UserModel.userRole(), query[0] ) )
            else:
               self.response.out.write('<font color=\"red\"><b>Selected city does not exist.</b></font>')

        elif action == 'showAll': #showAll # DONE
            showError = self.request.get('error') == 'True'
            if showError :
                  self.response.out.write('<font color=\"red\"><b>Selected city does not exist.</b></font>')
            query = cm.CityModel.all()
            if not showArchival:
                query.filter( 'archival =', False )
            name = self.request.get('name')
            if name:
              query.filter( 'name =', name )
            code = self.request.get('code')
            if code:
              query.filter( 'code =', code )
            adr = self.request.get('address')
            if adr:
              query.filter( 'positionText =', adr )
            self.response.out.write( cv.showAll(um.UserModel.userRole(), list(query) ) )

        elif action == 'edit': #edit/id/number #DONE
            ident = int( params[0] )
            self.response.out.write( cv.edit(EnhancedModel.queryLatest( cm.CityModel, ident).get()))

        elif action == 'delete': # delete/id/number # DONE
            city = EnhancedModel.queryLatest( cm.CityModel, ident=int(params[0])).get()
            self.response.out.write( cv.delete( city ))

        elif action == 'new': # new # DONE
            self.response.out.write( cv.new() )

    def post(self, action, *params, **kwds):
        permissionName = {"edit" : "ctEdit",
                            "delete" : "ctDelete",
                            "new": "ctNew",
                            "showAll": "ctShow"
                           }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You are not permitted to do this. Besides, you shouldn't see this message after all. </b></font>")
          return

        if action == 'new': # new # DONE
            city = cm.CityModel(
              name = cgi.escape(self.request.get( 'name' )),
              code = cgi.escape(self.request.get( 'code' )),
              positionText = cgi.escape(self.request.get('address')),
              position = maps.getGeoCoords(cgi.escape(self.request.get('address'))))
            city.put()
            ident = city.ident
            self.redirect(city.showLink()+'?done=True')
            
        elif action == 'edit': # edit/id/number # DONE
            old = EnhancedModel.queryLatest( cm.CityModel, ident = int( params[0] ) ).get() 
            new = cm.CityModel(
              name = cgi.escape(self.request.get( 'name' )),
              code = cgi.escape(self.request.get( 'code' )),
              positionText = cgi.escape(self.request.get('address')),
              position = maps.getGeoCoords(cgi.escape(self.request.get('address')))
                               )
            new.ident = old.ident
            EnhancedModel.deprecateOldVersion( new, old )
            self.redirect(new.showLink()+'?done=True')
            
        elif action == 'delete': # delete/id/number # DONE
            old = EnhancedModel.queryLatest( cm.CityModel, ident=int(params[0])).get()
            if old==None:
              self.redirect('/cities/showAll?error=True')
            else:
              if self.request.get('delete') == "NO":
                self.redirect(old.showLink())
              else:
                old.deleteInstance()
                self.redirect(old.showAllLink() + '?done=True')

        elif action == 'showAll': # DONE
           opt = '?archival='+cgi.escape(self.request.get('archival'))
           name = self.request.get('name')
           if name:
              opt += '&name='+ cgi.escape(name)
           code = self.request.get('code')
           if code:
              opt += '&code='+ cgi.escape(code)
           adr = self.request.get('address')
           if adr:
              opt += '&address='+ cgi.escape(adr)
           self.redirect('/cities/showAll'+opt)